<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:表格顶部插槽-->
      <template #headerTop>
        <!-- 子表单区域 -->
        <a-tabs type="card" v-model:activeKey="activeKey" animated @change="handleChangeTabs">
          <a-tab-pane tab="计划订单" key="plannedOrderTable" :forceRender="true"> </a-tab-pane>
          <!-- <a-tab-pane tab="采购需求" key="procurementRequirement" :forceRender="true"> </a-tab-pane> -->
          <a-tab-pane tab="供需明细表" key="supplyAndDemand" :forceRender="true">
            <div style="display: flex; justify-content: space-between">
              <div></div>
              <a-button type="primary" preIcon="ant-design:export-outlined" @click="handleExportXlsx('供需明细表', '/ps/psPlanningScheduling/exportSupplyDemand', { id });"> 导出</a-button>
            </div>
            <a-table
              v-if="activeKey === 'supplyAndDemand'"
              :dataSource="dataSourceTwo.data"
              :columns="supplyAndDemandColumns"
              :pagination="ipagination"
              @change="tableChange"
            />
          </a-tab-pane>
        </a-tabs>
      </template>
      <!--插槽:搜索-->
      <template #form-materialSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择料品编号" readonly @search="materialModalOpen" />
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined" v-if="hasPermission('ps:planOrder:add')"> 新增</a-button> -->
        <a-button
          type="primary"
          preIcon="ant-design:export-outlined"
          @click="onExportXls('selectPlanOrderId')"
          v-if="hasPermission('ps:planOrder:exportXls')"
        >
          导出</a-button
        >
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls" v-if="hasPermission('ps:planOrder:importExcel')"
          >导入</j-upload-button
        >
        <a-button type="primary" @click="handleRelease">释放请购</a-button>
        <!-- <a-button type="primary" @click="handleUnRelease" v-if="hasPermission('ps:planOrder:unRelease')">反释</a-button> -->

        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="batchHandleDelete" v-if="hasPermission('ps:planOrder:delete')">
                  <Icon icon="ant-design:delete-outlined"></Icon>
                  删除
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>批量操作
              <Icon icon="mdi:chevron-down"></Icon>
            </a-button>
        </a-dropdown> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
        <!-- <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" /> -->
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <PsPlanOrderModal @register="registerModal" @success="handleSuccess"></PsPlanOrderModal>
    <!-- MRP计算结果 -->
    <mrpResultModal @register="registerMrpResultModal" />
    <!-- 料品 -->
    <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" />
    <!-- 追溯 -->
    <fromTable :newId="newId" @register="formTableRegModal" />
    <!-- 单据类型 -->
    <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" />
  </div>
</template>

<script lang="ts" name="psPlanOrder-psPlanOrder" setup>
import { ref, reactive, toRaw, computed, unref } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import fromTable from './components/fromTable.vue';
import { useModal } from '/@/components/Modal';
import PsPlanOrderModal from './components/PsPlanOrderModal.vue';
import mrpResultModal from './components/mrpResultModal.vue';
import { columns, searchFormSchema, mrpResultColumns } from './PsPlanOrder.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, getPlanOrderResultList, releaseOrder, unReleaseOrder } from './PsPlanOrder.api';
import { defHttp } from '/@/utils/http/axios';
import { downloadFile } from '/@/utils/common/renderUtils';
import { usePermission } from '/@/hooks/web/usePermission';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import materialSelectModel from '/@/views/components/materialSelectModel.vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { setAdvancedQuery } from '/@/utils/util';
const { createMessage } = useMessage();
const { t } = useI18n();
const { hasPermission } = usePermission();
const checkedKeys = ref<Array<string | number>>([]);
const activeKey = ref('plannedOrderTable');
let supplyType = ref('');
//注册model
const [registerModal, { openModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [formTableRegModal, { openModal: openFromTable }] = useModal();
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
import { useMethods } from '/@/hooks/system/useMethods';
// 注册 结果
const [registerMrpResultModal, { openModal: openMrpResultModal }] = useModal();
const { handleExportXlsx } = useMethods();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '计划订单',
    api: getPlanOrderResultList,
    columns: mrpResultColumns,
    canResize: false,
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    showActionColumn: true,
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    // 请求之前对参数做处理
    // beforeFetch(params) {
    //   params.supplyType = supplyType.value;
    // },
  },
  exportConfig: {
    name: '计划订单',
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});
// 高级查询配置
const superQueryConfig = setAdvancedQuery(mrpResultColumns);

const dataSourceTwo = reactive({
  data: [],
});
//执行查询
function handleSuperQuery(params) {
  setProps({ searchInfo: toRaw(params) });
  reload();
}

const getPsProductionArrangementPlansDistributeList = () => {
  defHttp
    .get({
      url: '/ps/psPlanningScheduling/scheduling/getSupplyDemandList',
      params: {
        pageNo: ipagination.value.current,
        pageSize: ipagination.value.pageSize,
      },
    })
    .then((res) => {
      dataSourceTwo.data = res.records;
      ipagination.value.total = res.total;
    });
};
function tableChange(pagination) {
  ipagination.value.current = pagination.current;
  ipagination.value.pageSize = pagination.pageSize;
  getPsProductionArrangementPlansDistributeList();
}
const ipagination = ref({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30'],
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条';
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0,
});
const [registerTable, { getForm, reload, clearSelectedRowKeys, setProps }, { rowSelection, selectedRowKeys }] = tableContext;

const titleBox = document.getElementsByClassName('jeecg-basic-table-header__table-title-box');
const tableContainer = document.getElementsByClassName('ant-table-container');
const pagination = document.getElementsByClassName('ant-pagination');
const alertInfo = document.getElementsByClassName('ant-alert-info');

function handleChangeTabs(e) {
  // let showTable = false;
  activeKey.value = e;
  titleBox[0].style.display = e == 'supplyAndDemand' ? 'none' : 'flex';
  tableContainer[0].style.display = e == 'supplyAndDemand' ? 'none' : 'flex';
  tableContainer.length > 1 ? (tableContainer[1].style.display = e == 'supplyAndDemand' ? 'none' : 'flex') : '';
  pagination[0].style.display = e == 'supplyAndDemand' ? 'none' : 'flex';
  pagination.length > 1 ? (pagination[1].style.display = e == 'supplyAndDemand' ? 'none' : 'flex') : '';
  alertInfo[0].style.display = e == 'supplyAndDemand' ? 'none' : 'flex';
  // showTable = e == 'supplyAndDemand';
  if (e == 'plannedOrderTable') {
    
  }
  if (e == 'procurementRequirement') {
    
  }
  if (e === 'supplyAndDemand') {
    getPsProductionArrangementPlansDistributeList();
  }

 // setProps();
  reload();
}
/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
// 打开计划员筛选模态框
function materialModalOpen() {
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
function materialhandleSuccess(val, values) {
  getForm().setFieldsValue({
    materialCode: val[0].item.code,
  });
}
//释放订单
async function handleRelease() {
  const keys = unref(selectedRowKeys);
  const releaseType = unref(activeKey);
  if (!keys || keys.length == 0) {
    createMessage.warning(t('请先选择计划订单'));
  } else if (releaseType == 'plannedOrderTable') {
  //   openBillTypeModal(true, {
  //     isUpdate: false,
  //     showFooter: true,
  //     tableName: 'bus_product_order',
  //   });
  // } else if (releaseType == 'procurementRequirement') {
    openBillTypeModal(true, {
      isUpdate: false,
      showFooter: true,
      tableName: 'bus_buying_requisition,bus_buying_requisition_international,bus_buying_requisition_internal,bus_buying_requisition_afterSale',
    });
  }
}
const supplyAndDemandColumns = [
  {
    title: '供/需',
    dataIndex: 'type',
    key: 'type',
  },

  {
    title: '订单类型',
    dataIndex: 'way',
    key: 'way',
  },
  {
    title: '产品编码',
    key: 'productCode',
    dataIndex: 'productCode',
  },
  {
    title: '产品名称',
    key: 'productName',
    dataIndex: 'productName',
  },
  {
    title: '产品名称',
    key: 'drawingNo',
    dataIndex: 'drawingNo',
  },
  {
    title: '单位',
    key: 'uomName',
    dataIndex: 'uomName',
  },
  {
    title: '数量',
    key: 'qty',
    dataIndex: 'qty',
  },
  {
    title: '存储地点',
    key: 'whName',
    dataIndex: 'whName',
  },
  {
    title: '供应日期',
    key: 'srcDate',
    dataIndex: 'srcDate',
  },
  {
    title: '销售订单号',
    key: 'srcOrderNo',
    dataIndex: 'srcOrderNo',
  },
  {
    title: '销售订单行号',
    dataIndex: 'srcOrderRowNo',
    key: 'srcOrderRowNo',
  },
  {
    title: '来源单号',
    key: 'srcDocNo',
    dataIndex: 'srcDocNo',
  },
  {
    title: '来源单行号',
    dataIndex: 'srcDocRowNo',
    key: 'srcDocRowNo',
  },
];
//单据类型回写
async function billTypehandleSuccess(val, values) {
  let params = {
    resultIds: selectedRowKeys.value,
    billTypeId: val[0].value,
    releaseType: 1,
  };
  await releaseOrder(params);
  handleSuccess();
}

//反释订单
async function handleUnRelease() {
  if (selectedRowKeys.value.length > 0) {
    console.log('selectedRowKeys.value', selectedRowKeys.value);
    let params = {
      resultIds: selectedRowKeys.value.toString(),
    };
    unReleaseOrder(params);
    handleSuccess();
  } else createMessage.warning(t('请先选择数据'));
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
 */
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isDetail: true,
    isUpdate: true,
    showFooter: false,
  });
}
//  MRP计算结果
function handleMrpResult(record: Recordable) {
  openMrpResultModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '追溯',
      onClick: materialModalOpenFrom.bind(null, record),
    },
  ];
}
// const fromTableRef = ref(null)
const newId = ref();
function materialModalOpenFrom(record: Recordable) {
  newId.value = record.id;
  // fromTableRef.value.getList()
  openFromTable(true, {
    isUpdate: false,
    showFooter: true,
  });
  setTimeout(() => {
    newId.value = '';
  }, 200);
}
/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
    // {
    //   label: 'MRP计算结果',
    //   onClick: handleMrpResult.bind(null, record),
    // },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}
</script>

<style scoped></style>
